package service

import (
	"context"
	"fmt"
	"math/rand"
	"school/user-srv/basic/config"
	__ "school/user-srv/basic/proto"
	"school/user-srv/handler/models"
	"school/user-srv/pkg"
	"strconv"
	"time"
)

type Server struct {
	__.UnimplementedUserServer
}

func (s *Server) Login(_ context.Context, in *__.LoginReq) (*__.LoginResp, error) {
	var admin models.Admin
	if err := models.Login(&admin); err != nil {
		return nil, fmt.Errorf("登录失败")
	}
	return &__.LoginResp{
		Id: int64(admin.ID),
	}, nil
}
func (s *Server) SchoolAdd(_ context.Context, in *__.SchoolAddReq) (*__.SchoolAddResp, error) {
	school := models.School{
		Name:    in.Name,
		Address: in.Address,
		Static:  in.Static,
		Contact: in.Contact,
		Phone:   in.Phone,
	}
	if err := models.SchoolAdd(&school); err != nil {
		return nil, fmt.Errorf("添加失败")
	}
	return &__.SchoolAddResp{
		Id: int64(school.ID),
	}, nil
}
func (s *Server) SendSms(_ context.Context, in *__.SendSmsReq) (*__.SendSmsResp, error) {
	code := rand.Intn(9000) + 1000
	config.Rdb.Get(config.Ctx, "sendSms"+in.Mobile)
	sms, err := pkg.SendSms(in.Mobile, strconv.Itoa(code))
	if err != nil {
		return nil, err
	}
	if *sms.Body.Code != "OK" {
		return nil, fmt.Errorf(*sms.Body.Message)
	}
	config.Rdb.Set(config.Ctx, "sendSms"+in.Mobile, code, time.Minute*10)
	return &__.SendSmsResp{}, nil
}
func (s *Server) AdminList(_ context.Context, in *__.AdminReq) (*__.AdminResq, error) {
	var admin models.Admin
	if err := models.AdminList(&admin, in.Mobile); err != nil {
		return nil, fmt.Errorf("查询失败")
	}
	return &__.AdminResq{
		Username: admin.Username,
	}, nil
}

func (s *Server) SchoolList(_ context.Context, in *__.SchoolListReq) (*__.SchoolListResp, error) {
	var school []models.School
	if err := models.SchoolList(&school, int(in.Size), int(in.Page), in.Name); err != nil {
		return nil, fmt.Errorf("列表失败")
	}
	var Lists []*__.Lists
	for _, m := range school {
		list := __.Lists{
			Name:    m.Name,
			Address: m.Address,
			Static:  m.Static,
			Contact: m.Contact,
			Phone:   m.Phone,
		}
		Lists = append(Lists, &list)
	}
	return &__.SchoolListResp{
		List: Lists,
	}, nil
}
